var Project = {
    tableId: "projectTable"
};

var numberPage = 1;

function open_yusuan(ym,name,type){
    if(type=='1'){
        let index = layer.open({
            area: ['100%', '100%'],
            title: '门店['+name+']的预算',
            btn: ['关闭'],
            btnAlign: 'c',
            type: 2,
            async: false,
            content: "/zxYusuan/viewYuanSuanByYaoma?yaoma=" + ym,
            yes: function (index, layero) {
                layer.close(index);
            }
        });
    }else {
        let index = layer.open({
            area: ['50%', '80%'],
            title: '门店['+name+']的预算',
            btn: ['关闭'],
            btnAlign: 'c',
            type: 2,
            async: false,
            content: "/zxYusuan/viewYuanSuanByYaoma?yaoma=" + ym,
            yes: function (index, layero) {
                layer.close(index);
            }
        });
    }
}

layui.use(['table', 'admin', 'ax', 'form', 'layer', 'jquery'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var layer = layui.layer;

    /* leez */
    var windowClientWidth = document.body.clientWidth
    var windowClientWidthTemp = document.body.clientWidth
    var tableIsReloading = false

    function _reloadTable() {
        if(tableIsReloading) return
        tableIsReloading = true
        windowClientWidth = document.body.clientWidth;
        if(Math.abs(windowClientWidth - windowClientWidthTemp) > 20) {
            windowClientWidthTemp = windowClientWidth
        }
        setTimeout(() => {
            tableIsReloading = false
        }, 1500)
    }


    /**
     * 获取营运经理列表
     */
    var yyjlAjax = new $ax("/project/selectYyjlList");
    var yyjlResult = yyjlAjax.start();
    $.each(yyjlResult, function (index, data) {
        $("#yyjl").append("<option value='" + data.tel + "'>" + data.yyjl + "</option>");
    });
    form.render('select');

    /**
     * 初始化表格的列
     */
    Project.initColumn = function () {
        if(windowClientWidth < 771) {
            return [[
                {
                    templet: '#columnMini'
                }
            ]];
        } else {
            return [[
                {type: 'checkbox'},
                {type: 'numbers', title: '序号', align: "center", width: 50, hide: false},
                {field: 'name', sort: false, title: '门店名称', width: 200, align: "left", edit: 'text'},
                {align: 'center', toolbar: '#tableBar', title: '待办任务',  minWidth: '160', align: "left", style: 'overflow: auto;text-overflow: unset;white-space: break-spaces;'},
                {
                    sort: false,
                    title: `
<div class="line-box flex">
<span class="sTitle">开发<br/>区域<br/>经理</span>
<span class="sTitle">开发<br/>总监</span>
<span class="sTitle">工程<br/>总监 </span>
<span class="sTitle">营运<br/>总监</span>
<span class="sTitle">指定<br/>营运<br/>经理</span>
<span class="sTitle">指定<br/>督导</span>
<span class="sTitle">督导</span>
<span class="sTitle">完工<br/>时间</span>
<span class="sTitle">开业<br/>时间</span></div>`,
                    align: "left",
                    style: 'font-size: 11px',
                    templet: '#statusTpl',
                    width: 380,
                    style: 'padding-right: 0'
                },
                {field: 'yusuanHeji', sort: false, title: '预算合计(元)', width: 100, align: "left",templet: '#yusuanHejiTpl'},
                {field: 'jptime', sort: false, title: '接铺时间',width:100,align: "left"},
                {field: 'createUserName', toolbar: '#developUser', sort: false, title: '开发人员',width:100, align: "left"},
                {field: 'yyjlname', sort: false, title: '营运经理',width:100,  align: "left"},
                {field: 'createTime', sort: false, title: '建店时间', width: 150, align: "left"}
            ]];
        }

    };

    /**
     * 点击查询按钮
     */
    Project.search = function () {
        var jd= $('#jiedian option:selected') .val();
        var queryData = {};
        var pa = 1;
        queryData['condition'] = $("#condition").val();
        queryData['provinceName'] = $("#provinceName").val();
        queryData['cityName'] = $("#cityName").val();
        queryData['regionId'] = $("#regionName").val();
        queryData['name'] = $("#address").val();
        queryData['startWorkYn'] = $("#startWorkYn").val();
        queryData['cashierAccountYn'] = $("#cashierAccountYn").val();
        queryData['allStautusEnd'] = $("#allStautusEnd").val();
        queryData['status'] = $("#status").val();
        queryData['jdsj_px'] = $("#jdsj_px").val();
        queryData['jiedian'] =  $('#jiedian option:selected') .val();
        queryData['gcbcx'] =  $('#gcbcx option:selected') .val();

        /*table.reload(Project.tableId, {
            where: queryData, page: {curr: 1}
        });*/
        // Project.tableCfg.url=Feng.ctxPath + '/project/list';
        Project.tableCfg.where=queryData;
        table.render(Project.tableCfg);
        sessionStorage.setItem("gcglList",JSON.stringify(queryData));
    };

    /**
     * 弹出添加通知
     */
    var spectIds='2,19,3212,3213,3214,3219,3220,';//直辖市
    Project.openAddDlg = function () {
        var normal=false;
        var dm;
        var provinceName = $("#provinceName").val();
        if (provinceName == "") {
            Feng.error("请选择省!");
            return;
        }
        var cityName = $("#cityName").val();
        if (cityName == "") {
            Feng.error("请选择市!");
            return;
        }
        if(spectIds.indexOf(provinceName+',')==-1){
            normal=true;
        }
        if(isHasXianqu){
            var regionName = $("#regionName").val();
            if (regionName == ""&&normal) {
                Feng.error("请选择区县!");
                return;
            }
        }

        var address = $("#address").val();
        if (address == "") {
            Feng.error("请输入店名!");
            return;
        }
        var ptext=$("#provinceName").find("option:selected").text();
        var ctext=$("#cityName").find("option:selected").text();
        var rtext=$("#regionName").find("option:selected").text();
        if(rtext=="全部"){
            rtext = "";
        }
        var cityn='';
        var regionn='';
        if(normal){
            cityn=ctext.indexOf('市')>-1?ctext.substring(0,ctext.indexOf('市')):ctext;
            if(rtext.indexOf('区')>-1){
                regionn=rtext.substring(0,rtext.indexOf('区'));
            }else if(rtext.indexOf('市')>-1){
                regionn=rtext.substring(0,rtext.indexOf('市'));
            }else if(rtext.indexOf('县')>-1&&rtext.length>2){//沙县-两个字的县就带着
                regionn=rtext.substring(0,rtext.indexOf('县'));
            }else{
                regionn=rtext;
            }
        }else{
            //直辖市
            cityn=ptext;
            if(ctext.indexOf('区')>-1){
                regionn=ctext.substring(0,ctext.indexOf('区'));
            }else if(ctext.indexOf('县')>-1){
                regionn=ctext.substring(0,ctext.indexOf('县'));
            }else{
                regionn=ctext;
            }
        }
        if(!endsWith(address,'店')){
            address+="店";
        }
        dm=cityn+regionn+address;
        layer.confirm('店名：'+dm+'<br>是否使用此店名?',{title:'确认店名'}, function(index){
            var ajax1 = new $ax(Feng.ctxPath + "/project/addItem", function (data) {
                if (data.code == 1) {
                    Feng.error("添加失败!" + data.message + "!");
                    return;
                }
                Feng.success("添加成功!");
                table.reload(Project.tableId);
            }, function (data) {
                Feng.error("添加失败!" + data.responseJSON.message + "!");
            });
            ajax1.set("provinceName", ptext);
            ajax1.set("provinceId", $("#provinceName").val());
            ajax1.set("cityId", $("#cityName").val());
            ajax1.set("cityName", ctext);
            ajax1.set("regionId", $("#regionName").val());
            ajax1.set("regionName", rtext);
            ajax1.set('name', dm);
            ajax1.set('tel', $("#yyjl").val());
            ajax1.start();

            layer.close(index);
        });
    };
    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }
    var tip;
    Project.showTip=function(){
        tip=layer.tips('<div style="width: 180px;z-index: 99;"><div>店名请填写商超或标志性地标或XX路店</div><hr/>' +
            '<div>商超：如万达广场、恒隆广场、天街等</div><div>标志性地标：如花乡奥莱村、市民中心、奥体中心等</div>' +
            '<div>路：如南京路、江南大道、樱花巷等</div><hr/>' +
            '<div>例：万达广场店、花乡奥莱村店、南京路店</div></div>', '#address',{tips:[1,'#959595']});
    }

    $('#address').hover(function(){
        Project.showTip();
    },function () {
        layer.close(tip);
    });

    /**
     *批量隐藏接口 关店
     */
    Project.editStatus = function () {
        var checkRows = table.checkStatus(Project.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请至少选择一条数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/project/editBatch", function (data) {
                    Feng.success("修改成功!");
                    table.reload(Project.tableId);
                }, function (data) {
                    Feng.error("修改失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.set("status", 0);
                ajax.start();
            };
            Feng.confirm("确认要关闭选中的" + checkRows.data.length + "家店吗?", operation);
        }
    };

    /**
     *批量隐藏接口 开店
     */
    Project.openStatus = function () {
        var checkRows = table.checkStatus(Project.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请至少选择一条数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/project/editBatch", function (data) {
                    Feng.success("修改成功!");
                    table.reload(Project.tableId);
                }, function (data) {
                    Feng.error("修改失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.set("status", 1);
                ajax.start();
            };
            Feng.confirm("确认要开启选中的" + checkRows.data.length + "家店吗?", operation);
        }
    };

    /**
     * 导出excel按钮
     */
    Project.exportExcel = function () {
        var checkRows = table.checkStatus(Project.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击填表（商务）
     */
    Project.things = function (data) {
        window.location.href = Feng.ctxPath + '/project/things?id=' + data.id + "&swedit=" + data.swedit + "&auditbtn=" + data.auditbtn;
    };
    /**
     * 点击填表（商务条件新表格  商务基本信息表）
     */
     Project.swtjTable = function (data) {
        window.location.href = Feng.ctxPath + '/project/swtj?id=' + data.id + "&swedit=" + data.swedit + "&auditbtn=" + data.auditbtn+"&name="+encodeURI(data.name);
    };

    /**
     * 点击填表（工程）
     */
    Project.projectTerm = function (data) {
        //alert(data.auditbtn);
        window.location.href = Feng.ctxPath + '/project/projectTerm?id=' + data.id + "&gcedit=" + data.gcedit + "&auditbtn=" + data.auditbtn +"&auditbtn1=" + data.auditbtn1+ "&pageA=" + $('.layui-laypage .layui-laypage-curr').text();
    };

    /**
     * 点击跳转督导完成任务页面（需完成任务）
     */
    Project.steerTask = function (data) {
        window.location.href = Feng.ctxPath + '/task/steerTask?id=' + data.id;
    };

    /**
     * 点击跳转工程完成任务页面（工程需完成任务）
     */
    Project.projectTask = function (data) {
        window.location.href = Feng.ctxPath + '/task/projectTask?id=' + data.id;
    };

    //监听单元格编辑
    table.on('edit(projectTable)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        //编辑
        var number = $("#changeDM").children().length;
        if (number == 0) {
            //不含子元素
            layer.msg('您没有修改店名权限！', {icon: 2},);
            table.reload(Project.tableId);
        } else {
            //含有子元素
            $.ajax({
                type: "PUT",
                url: "/project/update",
                datatype: "json",
                data: data,
                async: false,
                success: function (res) {
                    if (res == false) {
                        Feng.error("修改失败！不允许重复店名！");
                    } else {
                        Feng.success("修改成功！");
                    }
                    table.reload(Project.tableId);
                }, error: function () {
                    Feng.error("修改失败！");
                }, complete: function (XHR, TS) {
                }

            });
        }

    });

    /**
     * 渲染表格
     */
    var pageLimit = 20;

    function checkConsole() {
        if (!window.console)
            window.console = {};
        var console = window.console;

        var funcs = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml',
            'error', 'exception', 'group', 'groupCollapsed', 'groupEnd',
            'info', 'log', 'markTimeline', 'profile', 'profileEnd',
            'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'
        ];
        for (var i = 0, l = funcs.length; i < l; i++) {
            var func = funcs[i];
            if (!console[func])
                console[func] = function() {};
        }
        if (!console.memory)
            console.memory = {};

    }

    let pageName = window.location.pathname.replace('/','')
    let pageInfo = localStorage.getItem(pageName + 'TablesLimit')

    var pageLimit = $(".layui-laypage-limits").find("option:selected").val()
    if(!pageInfo) {

    } else {
        // if((pageLimit !== pageInfo) && pageLimit !== 10) {
        // }
        pageLimit = pageInfo
    }

    localStorage.removeItem(pageName + 'TablesLimit');
    localStorage.setItem(pageName + 'TablesLimit', pageLimit);



    /**
     * 检索区域
     */
    var qyAjax = new $ax("/area/getAreaByType");
    qyAjax.set("type", 2);
    var qyResult = qyAjax.start();
    $.each(qyResult, function (index, data) {
        $("#provinceName").append("<option value='" + data.id + "'>" + data.simpleName + "</option>");
    });
    form.render('select');
    form.on('select(provinceName)', function (data) {
        var provinceId = data.value;
        isHasXianqu = false;
        if (provinceId == "") {
            $("#cityName").html("");
            $("#cityName").append("<option value=''>全部</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/area/getAreaByPid");
            qyAjax.set("pid", provinceId);
            var qyResult = qyAjax.start();
            $("#cityName").html("");
            $("#cityName").append("<option value=''>全部</option>");
            $.each(qyResult, function (index, data) {
                $("#cityName").append("<option value='" + data.id + "'>" + data.simpleName + "</option>");
            });
            form.render('select');
        }
    });
    var isHasXianqu = false;
    form.on('select(cityName)', function (data) {
        isHasXianqu = false;
        var cityId = data.value;
        if (cityId == "") {
            $("#regionName").html("");
            $("#regionName").append("<option value=''>全部</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/area/getAreaByPid");
            qyAjax.set("pid", cityId);
            var qyResult = qyAjax.start();
            $("#regionName").html("");
            $("#regionName").append("<option value=''>全部</option>");
            $.each(qyResult, function (index, data) {
                $("#regionName").append("<option value='" + data.id + "'>" + data.simpleName + "</option>");
                isHasXianqu = true;
            });
            form.render('select');
        }
    });

    var windowClientWidth = document.body.clientWidth
    var windowClientWidthTemp = document.body.clientWidth
    var tableIsReloading = false

    // leez 分页
    function getHashValue(key) {
        var matches = document.location.hash.match(new RegExp(key+'=([^&]*)'));
        return matches ? matches[1] : null;
    }

    var curr = 1
    var _iframe =  window.parent.document.querySelector('iframe[lay-id="/project"]')
    if(document.location.hash) {
        curr = document.location.hash.replace('#!fenye=', '')
    }

    Project.tableCfg={
        elem: '#' + Project.tableId,
        page: {
            // curr: location.hash.replace('#!fenye=', ''), //获取起始页
            curr: curr, //获取起始页
            hash: 'fenye' //自定义hash值
        },
        url:Feng.ctxPath + '/project/list',
        even: true,
        where:{allStautusEnd:$('#allStautusEnd').val(),status:$('#status').val()},
        limit: 20,//pageLimit=='undefined'?20:pageLimit,
        height: "full-55",
        cellMinWidth: 0,
        cols: Project.initColumn(),
        done: function (res, page, count) {

            curr = page

            $('#projectTable').hide()

            pageLimit = $(".layui-laypage-limits").find("option:selected").val()
            localStorage.removeItem(pageName + 'TablesLimit');
            localStorage.setItem(pageName + 'TablesLimit', pageLimit);

            if(windowClientWidth < 751) {
                $('.layui-table-view').addClass('miniHeight')
            } else {
                $('.layui-table-view').removeClass('miniHeight')
            }

            var number = $("#changeDM").children().length;
            let tableView = this.elem.next();
            layui.each(res.data, function (i, item) {
                if (number == 0) {
                    tableView.find('tr[data-index=' + i + ']').find('td').data('edit', false);
                }
            });
        }
    };

    // leez 延迟点击搜索
    let _init = false
    let _temp = admin.getTempData('indexTabs')

    _temp.map((item, i) => {
        if(item.menuId == '/project') {
            if(JSON.stringify(item).indexOf('currPage') != -1) { // 有上次存储的页码
                _init = true
                var  para = sessionStorage.getItem("gcglList");
                if(para!=null){
                    Project.tableCfg.url=Feng.ctxPath + '/project/list';
                    var p=JSON.parse(para);
                    Project.tableCfg.where=p;
                    if(p.provinceName!=''){
                        $('#provinceName').val(p.provinceName);
                    }
                    if(p.cityName!=''){
                        $('#cityName').val(p.cityName);
                    }
                    if(p.name!=''){
                        $('#address').val(p.name);
                    }
                    if(p.cashierAccountYn!=''){
                        $('#cashierAccountYn').val(p.cashierAccountYn);
                    }
                    if(p.allStautusEnd!=''){
                        $('#allStautusEnd').val(p.allStautusEnd);
                    }
                    if(p.startWorkYn!=''){
                        $('#startWorkYn').val(p.startWorkYn);
                    }
                    if(p.status!=''){
                        $('#status').val(p.status);
                    }
                    if(p.jdsj_px!=''){
                        $('#jdsj_px').val(p.jdsj_px);
                    }
                    form.render('select');
                }
                table.render(Project.tableCfg)
            } else {
                setTimeout(()=> {
                    document.querySelector('#btnSearch').click()
                    _init = true
                    // table.render(Project.tableCfg);
                },500)
            }
        }
    })

    setTimeout(() => {
        if(!_init) { // leez 这种情况出现在用户权限只有一个页面不能新建tab时
            table.render(Project.tableCfg)
        }
    }, 600)

    //返回保留条件查询

    // table.render(Project.tableCfg);

    /**
     * 搜索按钮点击事件
     */
    $('#btnSearch').click(function () {
        // $('#address').removeAttr('required');
        $('#jdsj_px').val("0");
        Project.search();
    });

    /**
     * 按建店时间排序
     */
    $('#orderbyJd').click(function () {
        $("#jdsj_px").val("1");
        Project.search();
    });

    /**
     * 关店按钮点击事件
     */
    $('#btnEdit').click(function () {
        // $('#address').removeAttr('required');
        Project.editStatus();
    });
    /**
     * 开店店按钮点击事件
     */
    $('#btnOpen').click(function () {
        // $('#address').removeAttr('required');
        Project.openStatus();
    });
    /**
     * 添加按钮点击事件
     */
    $('#btnAdd').click(function () {
        Project.openAddDlg();
    });

    $('#zdyyjl').click(function () {
        var checkRows = table.checkStatus(Project.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要指定的数据");
        }
        else if (checkRows.data.length > 1) {
            Feng.error("请选择一条数据");
        } else{
            Project.zdyyjl("营运经理", "0", "40",data[0].id);
        }

    });


    Project.zdyyjl = function (name, yyjl, taskId,id) {
        let url = "/project/saveGcyyjl";
        let type = "yyjl";
        if (yyjl != "0") {
            type = "dd";
            url = "/project/saveGcDd";
        }
        let index = layer.open({
            area: ['400px', '400px'],
            title: '指定' + name,
            btn: ['确定', '取消'],
            btnAlign: 'c',
            type: 2,
            async: false,
            content: "/project/zdyyjl?phone=" + yyjl,
            yes: function (index, layero) {
                var arr = $(layero).find("iframe")[0].contentWindow.back();
                var tel = $(layero).find("iframe")[0].contentWindow.backTel();
                var ajax = new $ax(url, function (msg) {
                    Feng.success("修改成功！");
                    layer.close(index);
                    table.reload(Project.tableId);
                    // parent.location.reload();
                }, function (data) {
                    alert("修改失败！" + data.responseJSON.message);
                    // layer.alert("修改失败！" + data.responslaypageeJSON.message,{ icon: 5, title: "提示", offset: "auto", skin: 'layui-layer-molv' });

                    // Feng.error("修改失败！" + data.responseJSON.message);
                });
                ajax.set(type, arr);
                ajax.set("tel", tel);
                ajax.set("id", id);
                ajax.set("taskId", taskId);
                ajax.start();
            }
        });
    };

    /**
     * 导出excel
     */
    $('#btnExp').click(function () {
        Project.exportExcel();
    });
    var _dataTable
    /**
     * 工具条点击事件
     */
    table.on('tool(' + Project.tableId + ')', function (obj) {
        // leez 页码存储
        let _temp = admin.getTempData('indexTabs')
        _temp.map((item, i) => {
            if(item.menuId == '/project') {
                _temp[i].currPage = curr
            }
        })
        admin.putTempData('indexTabs', _temp)


        var data = obj.data;
        var layEvent = obj.event;
        $("#ida").val(data.id);
        if (layEvent === 'viewShopByCreateUser') { // 20210927 leez新增 查看此开发人员负责的所有门店
            $.ajax({
                type: "get",
                url: "/gcH5/selectKfryList?userId=" + data.userId,
                async: true,
                success: function (res) {
                    if(res.success) {
                        let html = ''

                        html += '<div id="create-user-table" style="padding: 10px; font-size: 12px"><table><thead><tr><td>序号</td><td>店名</td><td>预算</td><td>报店日期</td><td>开业日期</td><td>状态</td></tr></thead><tbody>'
                        res.data.list.forEach((item, i) => {
                            let index = i + 1
                            let yaoma = item.yaoma ? '(妖码:' + item.yaoma + ')' : ''
                            let status = item.status == 1 ? '正常' : '已闭店'
                            let kyrq = item.openDate ? item.openDate.split(' ')[0] : ''
                            html += '<tr><td>' + index + '</td><td>' + item.name + '</td><td>' + item.yusuanHeji + '</td><td>' + item.createTime + '</td><td>' + kyrq + '</td><td>' + status + '</td></tr>'
                        })
                        html += '</tbody></table></div>'

                        try {
                            _dataTable.destroy()
                        } catch (error) {

                        }

                        layer.open({
                            type: 1,
                            title: data.createUserName + '负责的门店',
                            content: html,
                            area: ['800px', '600px']
                        })

                        setTimeout(() => {
                            _dataTable = $('#create-user-table table').DataTable({
                                "scrollY": "420px",
                                "scrollCollapse": true,
                                "columnDefs": [ {
                                    "targets": [0, 1],
                                    "orderable": true
                                } ],
                                language: {
                                    "sProcessing": "处理中...",
                                    "sLengthMenu": "显示 _MENU_ 项结果",
                                    "sZeroRecords": "没有匹配结果",
                                    "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                                    "sInfoPostFix": "",
                                    "sSearch": "搜索:",
                                    "sUrl": "",
                                    "sEmptyTable": "表中数据为空",
                                    "sLoadingRecords": "载入中...",
                                    "sInfoThousands": ",",
                                    "oPaginate": {
                                        "sFirst": "首页",
                                        "sPrevious": "上页",
                                        "sNext": "下页",
                                        "sLast": "末页"
                                    },
                                    "oAria": {
                                        "sSortAscending": ": 以升序排列此列",
                                        "sSortDescending": ": 以降序排列此列"
                                    }
                                }
                            });
                        }, 50)
                    }
                }
            })

        } else if (layEvent === 'manager') {
            Project.zhiDing("营运经理", "0", "40");
        } else if (layEvent === 'supervision') {
            Project.zhiDing("督导", data.yyjl, "41");
        } else if (layEvent === 'things') {
            Project.things(data);
        } else if (layEvent === 'swtjTable') {
            Project.swtjTable(data);
        } else if (layEvent === 'projectTerm') {
            Project.projectTerm(data);
        } else if (layEvent === 'open_yusuan') {
            alert("open_yusuan");
        } else if (layEvent === 'premises') {
            Project.premises(data);
        } else if (layEvent === 'steerTask') {
            Project.steerTask(data);
        } else if (layEvent === 'projectTask') {
            Project.projectTask(data);
        } else if (layEvent === 'examine') {
            let roleIds = $("#roleids").val().split(",");
            let msg = "";
            let taskId = "";
            for (let i = 0; i < roleIds.length; i++) {
                if (roleIds[i] == "1305422678196678657") {//营运总监
                    msg = "开发，工程总监已审核通过，是否开店";
                    taskId = "7";
                }
                /*
                if (roleIds[i] == "1305422111420379138") {//开发总监
                    msg = "商务条件已完成，是否确认通过";
                    taskId = "6";
                } else else if (roleIds[i] == "1305422420779659266") {//工程总监
                    msg = "工程条件已完成，是否确认通过";
                    taskId = "5";
                } else if (roleIds[i] == "1307580056085250050") {//网上建店
                    taskId = "43";
                }*/
            }
            let index = layer.open({
                area: ['300px', '250px'],
                title: '审核',
                btn: ['通过', '驳回'],
                btnAlign: 'c',
                type: 1,
                async: false,
                content: ' <div style="text-align:center;" id="div">\n' +
                    ' <span class="span" style="line-height: 150px;">' + msg + '</span>\n' +
                    ' <textarea type="text" hidden class="input" id="reason" placeholder="请填写驳回理由" style="height: 100px;width: 92%;margin-top: 10px;padding-left: 5px;"></textarea>\n' +
                    ' </div>',
                yes: function (index, layero) {
                    Project.shenHe(1, data.id, taskId);
                    table.reload(Project.tableId);
                    layer.close(index);
                },
                btn2: function (index, layero,) {
                    $('.input').show();
                    $('.span').hide();
                    var reason = $('#reason').val();
                    if (reason == '') {
                        $('.layui-layer-btn .layui-layer-btn0').hide();
                        $('.layui-layer-btn1').text('提交');
                        $('.layui-layer-btn1').css('background', '#1E9FFF');
                        $('.layui-layer-btn1').css('color', '#FFF');
                        layer.msg('请填写驳回理由！', {icon: 2},);
                        return false
                    } else {
                        Project.shenHe(0, data.id, taskId, $("#reason").val());
                        layer.close(index);
                    }
                },
            });
        }
    });

    /**
     * 审核
     */
    Project.shenHe = function (data, id, taskId, reason) {
        let obj = {};
        obj.proId = id;
        obj.status = data;
        obj.taskId = taskId;
        obj.content = reason;

        $.ajax({
            type: "post",
            url: "/taskStatus/audit",
            data: obj,
            async: false,
            success: function (rs) {
                if(rs.success){
                    if (data == 1) {
                        layer.msg('已确认！');
                    } else {
                        layer.msg('已驳回！');
                    }
                }else{
                    Feng.error(rs.message);
                }
                // parent.location.reload();
                table.reload(Project.tableId);
            }
        });
    };

    /**
     * 指定
     */
    Project.zhiDing = function (name, yyjl, taskId) {
        let url = "/project/saveGcyyjl";
        let type = "yyjl";
        if (yyjl != "0") {
            type = "dd";
            url = "/project/saveGcDd";
        }
        let index = layer.open({
            area: ['400px', '400px'],
            title: '指定' + name,
            btn: ['确定', '取消'],
            btnAlign: 'c',
            type: 2,
            async: false,
            content: "/project/zdyyjl?phone=" + yyjl,
            yes: function (index, layero) {
                var arr = $(layero).find("iframe")[0].contentWindow.back();
                var tel = $(layero).find("iframe")[0].contentWindow.backTel();
                var ajax = new $ax(url, function (msg) {
                    Feng.success("修改成功！");
                    layer.close(index);
                    table.reload(Project.tableId);
                    // parent.location.reload();
                }, function (data) {
                    alert("修改失败！" + data.responseJSON.message);
                    // layer.alert("修改失败！" + data.responslaypageeJSON.message,{ icon: 5, title: "提示", offset: "auto", skin: 'layui-layer-molv' });

                    // Feng.error("修改失败！" + data.responseJSON.message);
                });
                ajax.set(type, arr);
                ajax.set("tel", tel);
                ajax.set("id", $("#ida").val());
                ajax.set("taskId", taskId);
                ajax.start();
            }
        });
    };

    $("#appointMsg").on('click', function () {
        alert(1);
    });

    /**
     * 表单提交事件
     */
    // form.on('submit(btnSubmit)', function (data) {
    //     var ajax = new $ax(Feng.ctxPath + "/project/addItem", function (data) {
    //         Feng.success("添加成功！");
    //         window.location.href = Feng.ctxPath + '/project'
    //     }, function (data) {
    //         Feng.error("添加失败！" + data.responseJSON.message);
    //     });
    //     ajax.set(data.field);
    //     ajax.start();
    //     return false;
    // });

    /**
     * 是否闭店
     */
    form.on('select(cashierAccountYn)', function (data) {
        var cashierAccountYn = data.value;
        if (cashierAccountYn == 1) {
            $('#open').hide();
            $('#close').show();
        } else if (cashierAccountYn == 0) {
            $('#close').hide();
            $('#open').show();
        }
    });


    Project.reloadtable = function (page) {
        table.reload(Project.tableId, {
            where: queryData, page: {curr: page}
        });
    };

});
